package com.hzw.monitor.mysqlbinlog.utils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.hzw.monitor.mysqlbinlog.connection.ConnectionAttributes;
import com.hzw.monitor.mysqlbinlog.connection.ConnectionFactory;
import com.hzw.monitor.mysqlbinlog.netty.server.MyNioSocketChannel;
import com.hzw.monitor.mysqlbinlog.utils.StringUtils;
import com.hzw.monitor.mysqlbinlog.zookeeper.ZooKeeperUtils;

import io.netty.channel.ChannelHandlerContext;

public class NettyUtils {
	//
	private static final Logger logger = LogManager.getLogger(NettyUtils.class);

	// 清理channel的上下文环境
	public static void cleanChannelContext(ChannelHandlerContext ctx, Throwable cause) {
		ctx.close();
		ConnectionAttributes myAttributes = ((MyNioSocketChannel) ctx.channel()).getAttributes();
		ConnectionFactory.remove(StringUtils.union(myAttributes.getIp(), "" + myAttributes.getPort()));
		// 及时更新到ZK,写到哪算哪
		ZooKeeperUtils.update(myAttributes.getBinlogPositionZKPath(), myAttributes.getBinlogFileName() + ":"
				+ myAttributes.getBinlogPosition() + ":" + System.currentTimeMillis());
		// 通知其它人接力，如果需要的话
		ZooKeeperUtils.deletePath(myAttributes.getRunningZKPath());
		LoggerUtils.debug(logger, "channel is cleaned");
	}

	// 主动触发此连接的非注册
	public static void triggerChannelClosed(MyNioSocketChannel mySocketChannel) {
		if (null == mySocketChannel) {
			return;
		}
		LoggerUtils.debug(logger, "triggerChannelClosed");
		// 合法的
		// 这个runnable绝对是线程安全的 :)
		mySocketChannel.eventLoop().execute(new Runnable() {
			@Override
			public void run() {
				mySocketChannel.deregister();
				LoggerUtils.debug(logger, "deregister invoked");
			}
		});
	}

}
